import { MciInput } from '@/components/base';
import { ElTag, ElTooltip } from 'element-plus';
import { PropType } from 'vue';
import { IVariable } from './type';

export const VarSearch = defineComponent({
  props: {
    variables: {
      type: Array as PropType<IVariable[]>,
      default: () => []
    }
  },
  emits: ['var'],
  setup(props, { emit }) {
    // 搜索
    const source = ref('');
    // 变量
    const options = ref<IVariable[]>(props.variables || []);
    // 变量-搜索结果
    const filterOptions = computed(() => {
      return options.value.filter(
        (variable) => variable?.value?.includes(source.value) || variable?.label?.includes(source.value)
      );
    });

    watch(
      () => [props.variables],
      () => {
        if (props.variables) {
          options.value = props.variables;
        } else {
          options.value = [];
        }
      },
      { immediate: true }
    );

    return () => {
      return (
        <div class="w-full">
          <MciInput
            class="px-8"
            modelValue={source.value}
            placeholder="变量名称、中文名"
            delay={100}
            clearable={true}
            onChange-delay={(value) => {
              source.value = value;
            }}
          />

          {options.value && options.value.length > 0 && (
            <div class="h-200" style={{ overflowY: 'auto' }}>
              <div class="flex flex-wrap p-8">
                {filterOptions.value?.map((item: IVariable) => {
                  return (
                    <>
                      <ElTooltip effect="dark" content={item.label} placement="top">
                        <ElTag
                          type="info"
                          class={['cursor-pointer', 'mx-4', 'my-4']}
                          onClick={() => {
                            emit('var', item.value);
                          }}>
                          {item.value}
                        </ElTag>
                      </ElTooltip>
                    </>
                  );
                })}
              </div>
            </div>
          )}
        </div>
      );
    };
  }
});
